package top.jacktgq.hsp.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @Author CandyWall
 * @Date 2020/11/12--15:28
 * @Description 实现Http服务的处理器
 * 说明：1、SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 * 2、HttpObject 表示客户端和服务器端相互通讯的数据被封装成HttpObject
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    //读取客户端数据
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断msg是不是HttpRequest请求
        if (msg instanceof HttpRequest) {
            System.out.println("PipeLine hashcode：" + this.hashCode());

            System.out.println("msg 类型：" + msg.getClass());
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());

            //在浏览器中输入访问地址并回车，会执行两次Http请求，一次是请求数据，一次则是请求网页图标（favicon.ico)
            //所以可以把访问图标的请求给过滤了
            HttpRequest httpRequest = (HttpRequest) msg;
            //获取uri
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了 favicon.ico，不做响应");
                return;
            }

            //回复信息给浏览器[Http协议]
            //编码后的消息
            ByteBuf contentBuf = Unpooled.copiedBuffer("hello，我是netty编写的Http服务器", CharsetUtil.UTF_8);
            //构造HttpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, contentBuf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentBuf.readableBytes());
            //将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }
}
